package com.gientech.esexercise.controller;

import com.gientech.esexercise.entity.TestUser;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;

@RestController
public class TestUserController {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @GetMapping("/save")
    public String save(){

        TestUser user = new TestUser();
        user.setId("1");
        user.setName("王刚");
        user.setAge(18);
        user.setSex("男");
        user.setPhone("13189838909");

        //indexName默认取@Document中的indexName
        elasticsearchRestTemplate.save(user);

        //indexName动态指定--索引如果不存在save会自动创建后再存入数据
        elasticsearchRestTemplate.save(user, IndexCoordinates.of("test_user_info"));

        elasticsearchRestTemplate.save(user, IndexCoordinates.of("test_user_info_dd"));


        return "succ";
    }

    @GetMapping("/search")
    public Object search(){
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(queryBuilder);
        NativeSearchQuery searchQuery = builder.build();

        SearchHits<TestUser> user = elasticsearchRestTemplate.search(searchQuery, TestUser.class);

        //indexName动态指定
        SearchHits<TestUser> user_info = elasticsearchRestTemplate.search(searchQuery, TestUser.class,IndexCoordinates.of("test_user_info"));
        HashMap<Object,Object> objectHashMap = new HashMap<>();

        objectHashMap.put("test_user",user.getSearchHits());
        objectHashMap.put("test_user_info",user_info.getSearchHits());

        return objectHashMap;
    }

    @GetMapping("/delete")
    public String delete(){

        //根据ID删除-indexName默认取@Document中indexName
        elasticsearchRestTemplate.delete("1",TestUser.class);
        //根据ID删除-indexName动态指定
        elasticsearchRestTemplate.delete("1",IndexCoordinates.of("test_user_info"));

        return "delete_succ";
    }

}
